package in.muton.edushare.validators.formvalidators;

import in.muton.edushare.schedules.DateParser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;

import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.vo.Schedules;

public class DateDialogValidator extends AbstractFormValidator {
	private static Log log = LogFactory.getLog(DateDialogValidator.class);
	private static final long serialVersionUID = -6532612849437264783L;
	private final FormComponent<?>[] components;
	
	public DateDialogValidator(FormComponent<?> schStart, FormComponent<?> schEnd, 
			FormComponent<?> schRepetitionEnd,FormComponent<?> repetitionType) {
		super();
		this.components = new FormComponent<?>[] {schStart, schEnd,schRepetitionEnd,repetitionType};
	}

	public FormComponent<?>[] getDependentFormComponents() {
		// TODO Auto-generated method stub
		return components;
	}

	public void validate(Form<?> arg0) {
		Date schStart;
		try {
			schStart = DateParser.getDate(components[0].getInput());
		} catch (ParseException e) {
			throw new EduShareRuntimeException("Unable to parse date string");
		}
		Date schEnd;
		try {
			schEnd = DateParser.getDate(components[1].getInput());
		} catch (ParseException e) {
			throw new EduShareRuntimeException("Unable to parse date string");
		}
		Date repetitionEndDate;
		try {
			repetitionEndDate = DateParser.getDate(components[2].getInput());
		} catch (ParseException e) {
			throw new EduShareRuntimeException("Unable to parse date string");
		}
		Integer repetitionType = Integer.parseInt(components[3].getValue());		
		if(schStart.getTime() > schEnd.getTime()){
			error(components[1],"StartTimeError");
		}else if(schStart.getTime() > repetitionEndDate.getTime() && repetitionType!= Schedules.EVENT_ONCE_ONLY){
			error(components[2],"RepetitionTimeError");
		}else if(schStart.getTime() <  new Date().getTime()){
			error(components[0],"PastTimeError");
		}
	}
}
